package com.qf.shedule;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import org.apache.logging.log4j.core.tools.picocli.CommandLine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class MyLock {

    @Autowired
    RedisTemplate redisTemplate;

    private Integer num=0;

    //@Scheduled(cron = "* * * * * ?")
    public void mylock(){
        //设置锁 如果数据库中没有该key则设置成功！如果有则设置失败！
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", 1);
        //设置这把锁的过期时间，放置死锁的发生
        redisTemplate.expire("lock",30, TimeUnit.SECONDS);
        //如果为true则代表当前的线程获取到了这把锁
        if (lock){
            //执行自己的业务逻辑
            Boolean isnum = redisTemplate.hasKey("num");
            if (!isnum){
                redisTemplate.opsForValue().set("num",num);
            }else{
                //先获取
                num = Integer.valueOf(redisTemplate.opsForValue().get("num").toString());
                num=num+1;
                redisTemplate.opsForValue().set("num",num);
            }
            System.out.println("当前Num的值为："+num);
            //释放锁
            redisTemplate.delete("lock");
        }else{
            System.out.println("当前线程未获取到该锁!!!");
        }
    }

    /**
     * 1、简单任务示例（Bean模式）
     */
    @XxlJob("demoJobHandler")
    public ReturnT<String> demoJobHandler(String param) throws Exception {
        System.out.println("执行定时任务==================================");
        return ReturnT.SUCCESS;
    }

}
